package pl.drypisy;

import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import java.awt.image.Raster;

/**
 * Created with IntelliJ IDEA.
 * User: adam
 * Date: 08.01.13
 * Time: 19:30
 * Class for skewing image.
 */
public class ResizeProcess extends ImageProcess {
    private int width, height;
    private double xratio, yratio;

    BufferedImage src = null;

    public void setNewSize(int width, int height) {
        this.width = width;
        this.height = height;
    }

    public BufferedImage process(BufferedImage image) {
        this.src = image;
        srcWidth = src.getWidth();
        srcHeight = src.getHeight();
        BufferedImage dest = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        int[] outPixels = new int[width] ;
        int[] inPixels = src.getRGB(0, 0, srcWidth, srcHeight, null, 0, srcWidth);
        double out[] = new double[2];
        xratio = ((double)(srcWidth-1))/(double)width ;
        yratio = ((double)(srcHeight-1))/(double)height ;
        int nw, ne, sw, se;
        for (int y=0;y<height;y++) {
            for (int x=0;x<width;x++) {
                getOriginalCoordinates(x,y,out);
                int srcX = (int)Math.floor( out[0] );
                int srcY = (int)Math.floor( out[1] );
                int pix;
                if(doInterpolation) {
                    double xWeight = out[0]-srcX;
                    double yWeight = out[1]-srcY;
                    nw = getPixel( inPixels, srcX-1, srcY-1, srcWidth, srcHeight);
                    ne = getPixel( inPixels, srcX+1, srcY-1, srcWidth, srcHeight );
                    sw = getPixel( inPixels, srcX-1, srcY+1, srcWidth, srcHeight );
                    se = getPixel( inPixels, srcX+1, srcY+1, srcWidth, srcHeight );
                    pix = bilinearInterpolation(xWeight, yWeight,  nw, ne, sw, se);
                }
                else pix = getPixel(inPixels,srcX,srcY,srcWidth,srcHeight);
                outPixels[x] = pix;
            }
            dest.setRGB(0, y, width, 1, outPixels, 0, height);
        }
        return dest;
    }


    protected void getOriginalCoordinates(int x, int y, double out[])
    {
        out[0] = xratio * x;
        out[1] = yratio * y;
    }
}